<template>
  <div class="admin-login-container">
    <div class="login-card">
      <div class="login-header">
        <h1 class="login-title">管理员登录</h1>
        <p class="login-subtitle">PCB-CSM 后台管理系统</p>
      </div>
      
      <form @submit.prevent="handleLogin" class="login-form">
        <div class="form-group">
          <label for="username" class="form-label">用户名</label>
          <input
            id="username"
            v-model="loginForm.username"
            type="text"
            class="form-input"
            :class="{ 'error': errors.username }"
            placeholder="请输入管理员用户名"
            @blur="validateUsername"
          />
          <span v-if="errors.username" class="error-text">{{ errors.username }}</span>
        </div>
        
        <div class="form-group">
          <label for="password" class="form-label">密码</label>
          <div class="password-input-wrapper">
            <input
              id="password"
              v-model="loginForm.password"
              :type="showPassword ? 'text' : 'password'"
              class="form-input"
              :class="{ 'error': errors.password }"
              placeholder="请输入密码"
              @blur="validatePassword"
            />
            <button
              type="button"
              class="password-toggle"
              @click="togglePassword"
            >
              <i :class="showPassword ? 'fas fa-eye-slash' : 'fas fa-eye'"></i>
            </button>
          </div>
          <span v-if="errors.password" class="error-text">{{ errors.password }}</span>
        </div>
        
        <div class="form-group">
          <label class="checkbox-label">
            <input
              v-model="rememberMe"
              type="checkbox"
              class="checkbox-input"
            />
            <span class="checkbox-text">记住我</span>
          </label>
        </div>
        
        <button
          type="submit"
          class="login-button"
          :disabled="loading || !isFormValid"
          :class="{ 'loading': loading }"
        >
          <span v-if="loading" class="loading-spinner"></span>
          {{ loading ? '登录中...' : '登录' }}
        </button>
        
        <div v-if="errorMessage" class="error-message">
          {{ errorMessage }}
        </div>
      </form>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { adminAPI } from '@/api'

export default {
  name: 'AdminLoginView',
  setup() {
    const router = useRouter()
    const store = useStore()
    
    // 响应式数据
    const loginForm = ref({
      username: '',
      password: ''
    })
    
    const errors = ref({
      username: '',
      password: ''
    })
    
    const showPassword = ref(false)
    const rememberMe = ref(false)
    const loading = ref(false)
    const errorMessage = ref('')
    
    // 计算属性
    const isFormValid = computed(() => {
      return loginForm.value.username.length >= 3 && 
             loginForm.value.password.length >= 6 && 
             !errors.value.username && 
             !errors.value.password
    })
    
    // 方法
    const validateUsername = () => {
      if (!loginForm.value.username) {
        errors.value.username = '请输入用户名'
      } else if (loginForm.value.username.length < 3) {
        errors.value.username = '用户名至少3个字符'
      } else {
        errors.value.username = ''
      }
    }
    
    const validatePassword = () => {
      if (!loginForm.value.password) {
        errors.value.password = '请输入密码'
      } else if (loginForm.value.password.length < 6) {
        errors.value.password = '密码至少6个字符'
      } else {
        errors.value.password = ''
      }
    }
    
    const togglePassword = () => {
      showPassword.value = !showPassword.value
    }
    
    const handleLogin = async () => {
      // 验证表单
      validateUsername()
      validatePassword()
      
      if (!isFormValid.value) {
        return
      }
      
      loading.value = true
      errorMessage.value = ''
      
      try {
        const response = await adminAPI.login({
          username: loginForm.value.username,
          password: loginForm.value.password
        })
        
        if (response.success) {
          // 登录成功，保存管理员信息到store
          store.dispatch('loginAdmin', response.admin)
          
          // 如果选择了记住我，保存到localStorage
          if (rememberMe.value) {
            localStorage.setItem('adminCredentials', JSON.stringify({
              username: loginForm.value.username,
              rememberMe: true
            }))
          }
          
          // 跳转到管理员首页
          router.push('/admin/dashboard')
        } else {
          errorMessage.value = response.message || '登录失败'
        }
      } catch (error) {
        console.error('登录错误:', error)
        errorMessage.value = error.response?.data?.message || '登录失败，请检查网络连接'
      } finally {
        loading.value = false
      }
    }
    
    // 生命周期
    onMounted(() => {
      // 检查是否已经登录
      if (store.getters.isAdminLoggedIn) {
        router.push('/admin/dashboard')
        return
      }
      
      // 检查是否有保存的登录信息
      const savedCredentials = localStorage.getItem('adminCredentials')
      if (savedCredentials) {
        const credentials = JSON.parse(savedCredentials)
        if (credentials.rememberMe) {
          loginForm.value.username = credentials.username
          rememberMe.value = true
        }
      }
    })
    
    return {
      loginForm,
      errors,
      showPassword,
      rememberMe,
      loading,
      errorMessage,
      isFormValid,
      validateUsername,
      validatePassword,
      togglePassword,
      handleLogin
    }
  }
}
</script>

<style scoped>
.admin-login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #1e293b 0%, #334155 40%, #475569 100%);
  padding: 20px;
  position: relative;
  overflow: hidden;
}

.admin-login-container::before {
  content: '';
  position: absolute;
  top: -50%;
  left: -50%;
  width: 200%;
  height: 200%;
  background: radial-gradient(circle, rgba(59, 130, 246, 0.08) 0%, transparent 70%);
  animation: rotate 30s linear infinite;
}

@keyframes rotate {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.login-card {
  background: rgba(30, 41, 59, 0.9);
  border: 1px solid rgba(148, 163, 184, 0.2);
  border-radius: 20px;
  padding: 40px;
  width: 100%;
  max-width: 400px;
  box-shadow: 0 25px 50px rgba(0, 0, 0, 0.25);
  backdrop-filter: blur(20px);
  position: relative;
  z-index: 1;
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-title {
  font-size: 28px;
  font-weight: 700;
  background: linear-gradient(135deg, #60a5fa 0%, #3b82f6 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  margin-bottom: 8px;
}

.login-subtitle {
  color: #94a3b8;
  font-size: 14px;
  margin: 0;
}

.login-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-label {
  font-weight: 600;
  color: #e2e8f0;
  font-size: 14px;
}

.form-input {
  padding: 12px 16px;
  border: 2px solid rgba(148, 163, 184, 0.3);
  border-radius: 10px;
  font-size: 16px;
  transition: all 0.3s ease;
  background: rgba(51, 65, 85, 0.5);
  color: #e2e8f0;
}

.form-input::placeholder {
  color: #94a3b8;
}

.form-input:focus {
  outline: none;
  border-color: #3b82f6;
  background: rgba(51, 65, 85, 0.8);
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.form-input.error {
  border-color: #e74c3c;
  background: #fdf2f2;
}

.password-input-wrapper {
  position: relative;
}

.password-toggle {
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  color: #666;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  transition: color 0.3s ease;
}

.password-toggle:hover {
  color: #333;
}

.checkbox-label {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  font-size: 14px;
  color: #666;
}

.checkbox-input {
  width: 16px;
  height: 16px;
  accent-color: #667eea;
}

.checkbox-text {
  user-select: none;
}

.login-button {
  background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
  color: white;
  border: none;
  padding: 14px 20px;
  border-radius: 10px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  margin-top: 10px;
  box-shadow: 0 4px 14px rgba(59, 130, 246, 0.2);
}

.login-button:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(59, 130, 246, 0.4);
  background: linear-gradient(135deg, #2563eb 0%, #1e40af 100%);
}

.login-button:disabled {
  opacity: 0.7;
  cursor: not-allowed;
  transform: none;
}

.login-button.loading {
  pointer-events: none;
}

.loading-spinner {
  width: 16px;
  height: 16px;
  border: 2px solid transparent;
  border-top: 2px solid white;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.error-text {
  color: #e74c3c;
  font-size: 12px;
  margin-top: 4px;
}

.error-message {
  background: #fdf2f2;
  color: #e74c3c;
  padding: 12px;
  border-radius: 8px;
  font-size: 14px;
  text-align: center;
  border: 1px solid #fadbd8;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .admin-login-container {
    padding: 10px;
  }
  
  .login-card {
    padding: 30px 20px;
  }
  
  .login-title {
    font-size: 24px;
  }
}

/* Font Awesome 图标 */
@import url('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css');
</style> 